package cn.itrip.order.controller;

import cn.itrip.dao.ItripHotelOrderMapper;
import cn.itrip.dao.ItripHotelRoomMapper;
import cn.itrip.dao.ItripUserLinkUserMapper;
import cn.itrip.dto.Dto;
import cn.itrip.order.service.OrderService;
import cn.itrip.pojo.*;
import cn.itrip.utlis.*;
import cn.itrip.vo.ItripHotelOrderInfo;
import cn.itrip.vo.OrderSelectCondition;
import cn.itrip.vo.order.*;
import cn.itrip.vo.store.StoreVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/api")
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private ValidationToken validationToken;
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private ItripHotelRoomMapper itripHotelRoomMapper;

    /**
     * "根据id查询个人订单详情
     * @param orderId
     * @param request
     * @return
     */
    @ApiOperation(value="根据id查询个人订单详情",httpMethod = "GET", protocols = "HTTP", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/getpersonalorderinfo/{orderId}",method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto getpersonalorderinfo(@PathVariable String orderId,HttpServletRequest request){

        //根据id查询订单的信息
        ItripHotelOrder itripHotelOrder = orderService.findByOrderId1(Long.parseLong(orderId));
        if (itripHotelOrder != null) {
            ItripPersonalHotelOrderVO orderVO = new ItripPersonalHotelOrderVO();
            orderVO.setId(itripHotelOrder.getId());
            orderVO.setBookType(itripHotelOrder.getBooktype());
            orderVO.setCreationDate(itripHotelOrder.getCreationdate());
            orderVO.setOrderNo(itripHotelOrder.getOrderno());
            //根据房间的id查询房间的信息
            ItripHotelRoom hotelRoom = itripHotelRoomMapper.selectByPrimaryKey(itripHotelOrder.getRoomid());
            Integer orderStatus = itripHotelOrder.getOrderstatus();
            orderVO.setOrderStatus(orderStatus);
            if (hotelRoom != null) {
                orderVO.setRoomPayType(hotelRoom.getPaytype());
             }
             if (orderStatus == 1) {
                orderVO.setProcessNode("3");
             }else if (orderStatus == 0) {
                    orderVO.setProcessNode("2");
             }else if (orderStatus == 2) {
                    orderVO.setProcessNode("3");
             }else if (orderStatus == 3) {
                    orderVO.setProcessNode("5");
             }else if (orderStatus == 4) {
                    orderVO.setProcessNode("6");
             } else if (orderStatus==null){
                    orderVO.setProcessNode(null);
             }
             orderVO.setPayAmount(itripHotelOrder.getPayamount());
             orderVO.setPayType(itripHotelOrder.getPaytype());
             orderVO.setNoticePhone(itripHotelOrder.getNoticephone());
             return DtoUtils.returnSuccess("获取订单信息成功！！！", orderVO);
            } else {
                return DtoUtils.returnFail("获取订单信息失败！！！", "100011");
            }
    }
    /**
     *  根据条件查询订单列表，并分页显示
     *  第一次进入，默认值：起始位置0   页码容量20
     *  pageSize   页码容量
     *  pageNo   当前页码
     * @param itripSearchOrderVO
     * @param request
     * @return
     */
    @ApiOperation(value = "根据条件查询订单列表，并分页显示",httpMethod = "POST", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/getpersonalorderlist" ,method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto getpersonalorderlist(@RequestBody ItripSearchOrderVO itripSearchOrderVO, HttpServletRequest request){
        String token=request.getHeader("token");
        ItripUser itripUser=validationToken.getCurrentUser(token);
        if (itripUser==null){
            return DtoUtils.returnFail("token已过期，请重新登陆！","100010");
        }
        OrderSelectCondition orderSelectCondition=new OrderSelectCondition();
        List<ItripHotelOrder> list=new ArrayList();
        try {
            orderSelectCondition.setOrderType(itripSearchOrderVO.getOrderType());
            orderSelectCondition.setStartDate(itripSearchOrderVO.getStartDate());
            orderSelectCondition.setEndDate(itripSearchOrderVO.getEndDate());
            orderSelectCondition.setInkUserName(itripSearchOrderVO.getLinkUserName());
            orderSelectCondition.setOrderNo(itripSearchOrderVO.getOrderNo());
            orderSelectCondition.setOrderStatus(itripSearchOrderVO.getOrderStatus());
            orderSelectCondition.setUserId(itripUser.getId());
            Integer pageNo=itripSearchOrderVO.getPageNo();
            if (pageNo==null){
                pageNo=1;
            }
            Integer pageSize=itripSearchOrderVO.getPageSize();
            Page<ItripListHotelOrderVO> page=orderService.findOrderBypage(orderSelectCondition,pageNo,pageSize);
            return DtoUtils.returnSuccess("获取个人订单信息成功！！！",page);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"获取个人订单信息失败");
        }
    }

    /**
     *根据订单id获取订单订单详情
     * @param orderId
     * @param request
     * @return
     */
    @ApiOperation(value = "根据订单id获取订单详情",httpMethod = "GET", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/queryOrderById/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto queryOrderById(@PathVariable String orderId,HttpServletRequest request){

        ItripModifyHotelOrderVO itripModifyHotelOrderVO=new ItripModifyHotelOrderVO();
        List<ItripOrderLinkUserVo> linkUserVos= null;
        try {

            String tokenString = request.getHeader("token");
            ItripUser currentUser = validationToken.getCurrentUser(tokenString);
            if(currentUser==null){
                return DtoUtils.returnFail("token失效，请重登录", "100000");
            }
            ItripHotelOrder itripHotelOrder=orderService.findByOrderId1(Long.parseLong(orderId));
            itripModifyHotelOrderVO.setNoticePhone(itripHotelOrder.getNoticephone());
            itripModifyHotelOrderVO.setBookingDays(itripHotelOrder.getBookingdays());
            itripModifyHotelOrderVO.setBookType(itripHotelOrder.getBooktype());
            itripModifyHotelOrderVO.setCheckInDate(itripHotelOrder.getCheckindate());
            itripModifyHotelOrderVO.setCheckOutDate(itripHotelOrder.getCheckoutdate());
            itripModifyHotelOrderVO.setCount(itripHotelOrder.getCount());
            itripModifyHotelOrderVO.setHotelId(itripHotelOrder.getHotelid());
            itripModifyHotelOrderVO.setHotelName(itripHotelOrder.getHotelname());
            itripModifyHotelOrderVO.setId(itripHotelOrder.getId());
            itripModifyHotelOrderVO.setInvoiceHead(itripHotelOrder.getInvoicehead());
            itripModifyHotelOrderVO.setInvoiceType(itripHotelOrder.getInvoicetype());
            itripModifyHotelOrderVO.setIsNeedInvoice(itripHotelOrder.getIsneedinvoice());
            itripModifyHotelOrderVO.setLinkUserName(itripHotelOrder.getLinkusername());
            itripModifyHotelOrderVO.setNoticeEmail(itripHotelOrder.getNoticeemail());
            itripModifyHotelOrderVO.setOrderNo(itripHotelOrder.getOrderno());
            itripModifyHotelOrderVO.setPayType(itripHotelOrder.getPaytype());
            itripModifyHotelOrderVO.setRoomId(itripHotelOrder.getRoomid());
            itripModifyHotelOrderVO.setSpecialRequirement(itripHotelOrder.getSpecialrequirement());
            linkUserVos = orderService.findLinkUserByUserId(currentUser.getId());
            itripModifyHotelOrderVO.setItripOrderLinkUserList(linkUserVos);
            return DtoUtils.returnDataSuccess(itripModifyHotelOrderVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"获取订单信息失败");
        }
    }

    /**
     * 生成订单前获取预定信息
     */
    @ApiOperation(value="生成订单前获取预定信息",httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/getpreorderinfo",method = RequestMethod.POST,produces ="application/json")
    @ResponseBody
    public Dto<RoomStoreVO> getpreorderinfo(@RequestBody ValidateRoomStoreVO validateRoomStoreVO, HttpServletRequest request)throws Exception{
        String token=request.getHeader("token");
        ItripUser currerUser=validationToken.getCurrentUser(token);
        if (currerUser==null){
            return DtoUtils.returnFail("token已过期，请重新登陆","100010");
        }
        RoomStoreVO roomStoreVO=new RoomStoreVO();
        ItripHotel hotel=orderService.findByHotelId(validateRoomStoreVO.getHotelId());
        ItripHotelRoom room=orderService.findByRoomId(validateRoomStoreVO.getRoomId());
        List<StoreVO> storeVOList=orderService.findByQuery(validateRoomStoreVO);
        roomStoreVO.setCheckInDate(validateRoomStoreVO.getCheckInDate());
        roomStoreVO.setCheckOutDate(validateRoomStoreVO.getCheckOutDate());
        roomStoreVO.setHotelName(hotel.getHotelname());
        roomStoreVO.setRoomId(room.getId());
        roomStoreVO.setPrice(room.getRoomprice());
        roomStoreVO.setHotelId(validateRoomStoreVO.getHotelId());
        roomStoreVO.setCount(1);
        roomStoreVO.setStore(storeVOList.get(0).getStore());
        if (storeVOList.size()==0){
            return DtoUtils.returnFail("暂时无房","100011");
        }
        return DtoUtils.returnSuccess("获取成功",roomStoreVO);
    }

    /**
     * 改变日期验证房间库存
     * @param validateRoomStoreVO
     * @param request
     * @return
     */
    @ApiOperation(value="改变日期验证房间库存",httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/validateroomstore", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Map<String, Boolean>> validateRoomStore(@RequestBody ValidateRoomStoreVO validateRoomStoreVO, HttpServletRequest request) {
        try {
                String token=request.getHeader("token");
                ItripUser currerUser=validationToken.getCurrentUser(token);
                if (currerUser==null){
                return DtoUtils.returnFail("token已过期，请重新登陆","100010");
                }
                boolean flag=false;
                List<StoreVO> storeVOList=orderService.findByQuery(validateRoomStoreVO);
                if(storeVOList!=null)
                {
                    flag=true;
                }
                Map<String, Boolean> map = new HashMap<String, Boolean>();
                map.put("flag", flag);
               return DtoUtils.returnSuccess("操作成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail("系统异常", "100517");
        }
    }

    /**
     * 添加订单信息
     * @param itripAddHotelOrderVO 用户填入信息的实体类VO
     * @param request
     * @return  Dto
     * @throws ParseException
     * ItripHotelOrder  sql语句查询使用的实体类  pojo
     */
    @ApiOperation(value = "根据用户填入的信息，生成新的订单",httpMethod = "GET", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/addhotelorder",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto addhostelorder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO,HttpServletRequest request) throws ParseException {
        String token=request.getHeader("token");
        ItripUser currerUser=validationToken.getCurrentUser(token);
        if (currerUser==null){
            return DtoUtils.returnFail("token已过期，请重新登陆","100010");
        }
        ItripHotelRoom itripHotelRoom=itripHotelRoomMapper.selectByPrimaryKey(itripAddHotelOrderVO.getRoomId());
        //根据用户id查取用户相关信息
        ItripHotelOrder itripHotelOrder=new ItripHotelOrder();
        itripHotelOrder.setUserid(currerUser.getId());
        //生成订单编号
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(itripAddHotelOrderVO.getCheckInDate());
        String val = "";
        String hand="D1000001";
        Random random=new Random();
        for(int i=0;i<6;i++){
            String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
            if ( "char".equalsIgnoreCase( str ) )
            { // 产生字母
                int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
                val += (char) ( nextInt + random.nextInt( 26 ) );
            }
            else if ( "num".equalsIgnoreCase( str ) )
            { // 产生数字
                val += String.valueOf( random.nextInt( 10 ) );
            }
        }
        itripHotelOrder.setOrderno(hand+newDate+val);
        //随机生成交易单号
        String s = "";
        Random suiji = new Random();
        s+=suiji.nextInt(9)+1;
        for (int i = 0; i < 18-1; i++) {
            s+=suiji.nextInt(10);
        }
        itripHotelOrder.setTradeno(s);
        itripHotelOrder.setHotelid(itripAddHotelOrderVO.getHotelId());
        itripHotelOrder.setHotelname(itripAddHotelOrderVO.getHotelName());
        itripHotelOrder.setRoomid(itripAddHotelOrderVO.getRoomId());
        itripHotelOrder.setCount(itripAddHotelOrderVO.getCount());
        itripHotelOrder.setOrdertype(1);
        //预定天数
        itripHotelOrder.setCheckindate(itripAddHotelOrderVO.getCheckInDate());
        itripHotelOrder.setCheckoutdate(itripAddHotelOrderVO.getCheckOutDate());
        Date start=itripAddHotelOrderVO.getCheckInDate();
        Date end=itripAddHotelOrderVO.getCheckOutDate();
        int day=DateUtils.getBetweenDates(start,end).size();
        itripHotelOrder.setBookingdays(day);
        //计算价钱
        int a=itripHotelRoom.getRoomprice().intValue();
        int price= a*day;
        BigDecimal c = new BigDecimal(price);
        itripHotelOrder.setPayamount(c);
        itripHotelOrder.setOrderstatus(0);
        itripHotelOrder.setPaytype(itripHotelRoom.getPaytype());
        itripHotelOrder.setNoticephone(itripAddHotelOrderVO.getNoticePhone());
        itripHotelOrder.setNoticeemail(itripAddHotelOrderVO.getNoticeEmail());
        itripHotelOrder.setBooktype(itripHotelRoom.getIsbook());
        itripHotelOrder.setCreationdate(new Date());
        itripHotelOrder.setCreatedby(currerUser.getId());
        itripHotelOrder.setSpecialrequirement(itripAddHotelOrderVO.getSpecialRequirement());
        StringBuilder linkUserName = new StringBuilder();
        int size = itripAddHotelOrderVO.getLinkUser().size();
        //旅客的名字
        for (int i = 0; i < size; i++) {
            if (i != size - 1) {
                linkUserName.append(itripAddHotelOrderVO.getLinkUser().get(i).getLinkusername() + ",");
            } else {
                linkUserName.append(itripAddHotelOrderVO.getLinkUser().get(i).getLinkusername());
            }
        }
        itripHotelOrder.setLinkusername(linkUserName.toString());
        //执行sql语句   返回的增加结果
        int number=itripHotelOrderMapper.insertSelective(itripHotelOrder);
        if (number==0){
            return DtoUtils.returnFail("添加订单信息失败","100013");
        }
        ItripHotelOrderInfo itripHotelOrderInfo=new ItripHotelOrderInfo();
        itripHotelOrderInfo.setId(itripHotelOrder.getId());
        itripHotelOrderInfo.setOrderNo(itripHotelOrder.getOrderno());
        return DtoUtils.returnSuccess("添加订单信息成功", itripHotelOrderInfo);
    }
    /***
     *如果达到 2 小时仍未支付，该订单自动转变为已取消状态,未支付订单中预订的房间会减库存，释放所预订的房间。
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void flushCancleOrderStatus() {
        try {
            orderService.flushCancleOrderStatus();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /***
     * 2秒执行一次 大于退房时间变成待评价
     */
    @Scheduled(cron = "*0 0/2 * * * ?")
    public void flushCommentlOrderStatus() {
        try {
          orderService.flushCommentlOrderStatus();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据订单id获取订房间信息（入住信息）
     * @param orderId
     * @param request
     * @return
     */
    @ApiOperation(value = "根据订单id获取订房间信息（入住信息）",httpMethod = "GET", produces = "application/json", response = Dto.class)
    @RequestMapping(value = "/hotelorder/getpersonalorderroominfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto getPersonalOrderRoomInfo(@PathVariable String orderId,HttpServletRequest request)
    {
        Dto dto=new Dto();
        String tokenString = request.getHeader("token");
        ItripUser currentUser = validationToken.getCurrentUser(tokenString);
        if (currentUser==null){
            return DtoUtils.returnFail("token已过期，请重新登陆！！！","100010");
        }
        try {
            ItripPersonalOrderRoomVO vo = orderService.getItripHotelOrderRoomInfoById(Long.valueOf(orderId));
            if (null != vo) {
                dto= DtoUtils.returnSuccess("获取个人订单房型信息成功", vo);
            }
            else
            {
                dto= DtoUtils.returnSuccess("获取信息成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
               dto= DtoUtils.returnFail("获取个人订单房型信息错误", "100531");
        }
        return dto;
    }
}
